<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { useIcon } from '@/hooks/web/useIcon'
import { Table } from '@/components/Table'
import {
  ElButton, ElCheckbox, ElDivider, ElDropdown, ElDropdownItem, ElDropdownMenu,
  ElForm, ElFormItem, ElInput, ElOption, ElSelect,
  ElSpace, ElUpload, ElMessage
} from 'element-plus'
import { h, reactive, ref, unref, watch } from 'vue'
import { useTable } from "@/hooks/web/useTable";
import { WorkControlData, WorkData } from "@/api/manage/work/types";
import {
  delWorkApi, getWorkListApi, saveOrUpdate, getWorkDetailApi
  , getWorkControlApi, saveWorkControlApi
} from "@/api/manage/work";
import { Pagination, TableColumn } from "@/types/table";
import Edit from "./edit.vue";
import { Dialog } from '@/components/Dialog'
import { FormSchema } from "@/types/form";
import { useValidator } from "@/hooks/web/useValidator";
import EditControl from "./editControl.vue";
import { downloadStatic } from "@/api/common/index"
import { OrgData } from "@/api/org/types";
import { getSelectOrgListApi } from "@/api/org/index";
import { PATH_URL } from '@/config/axios/service'

// 沙箱管理

const { required } = useValidator()

const queryModel = reactive<Recordable>({
  company_id: '',
  alias: ''
})
const stateOptions = [
  { label: '正常', value: 1301 },
  { label: '被禁用', value: 1302 },
  { label: '未授权', value: 1303 },
  { label: '未启动', value: 1304 },
  { label: '未知', value: 1305 }
];
const columns = reactive<TableColumn[]>([
  {
    field: 'user_id',
    label: '沙箱ID',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'alias',
    label: '别名',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'state',
    label: '状态',
    visible: true,
    className: ''
  }, {
    field: 'company_id',
    label: '组织ID',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'data_service_list',
    label: '可使用的密文端',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'storage',
    label: '已用/总空间(GB)',
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: ''
  }
])

const { register, tableObject, methods } = useTable<WorkData>({
  getListApi: getWorkListApi,
  delListApi: delWorkApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { getList, setSearchParams } = methods
getList()

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' }),
  deleteIcon: useIcon({ icon: 'ep:delete' }),
  controlIcon: useIcon({ icon: 'carbon:settings-adjust' }),
  playIcon: useIcon({ icon: 'material-symbols:play-circle' }),
  stopIcon: useIcon({ icon: 'material-symbols:stop-circle' })
}
const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  let queryParams: Recordable = {} as any
  if (queryModel.column) {
    queryParams[queryModel.column] = queryModel.val
  }
  setSearchParams({ queryParams })
}

const selectedCount = ref(0)
const multipleSelection = ref<WorkData[]>([])
const handleSelectionChange = (val: WorkData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleVisibleChange = (item) => {
  item.className = item.visible ? '' : 'hidden'
}

const dialogVisible = ref(false);
const dialogTitle = ref("");
const actionType = ref("");
const loading = ref(false)
const delLoading = ref(false)
const editRef = ref<ComponentRef<typeof Edit>>()

const save = async () => {
  const form = unref(editRef)
  await form?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await form?.getFormData()) as WorkData
      const isUpdate = actionType.value == 'edit';
      const res = await saveOrUpdate(data, isUpdate)
        .catch(() => {
        })
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.page_index = 1
        handleQuery();
        ElMessage.success(res.msg);
      }
    }
  })
}
const handleAdd = () => {
  tableObject.currentRow = null
  actionType.value = ''
  dialogTitle.value = '新增沙箱'
  dialogVisible.value = true
}
const handleEditButton = async (row: WorkData) => {
  loading.value = true;
  const res = await getWorkDetailApi(row.user_id, row.company_id).catch(() => { }).finally(() => {
    loading.value = false;
  })
  if (res) {
      tableObject.currentRow = res.data
      actionType.value = 'edit'
      dialogTitle.value = '修改沙箱'
      dialogVisible.value = true
  } else {
    ElMessage.error("加载数据失败，请联系管理员！");
  }

}
const handleDeleteButton = async (row: WorkData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delListByObj, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delListByObj(
    multiple ? selections : [row] as WorkData[],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const formSchema = reactive<FormSchema[]>([
  {
    field: 'user_id',
    label: '沙箱ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'domain',
    label: '沙箱登录账号',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'key',
    label: '沙箱密码',
    component: 'InputPassword',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'company_id',
    label: '组织ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'alias',
    label: '沙箱别名',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'tel',
    label: '管理电话',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'mail',
    label: '管理邮箱',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'user_type',
    label: '用户类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '普通用户',
          value: 1
        },
        {
          label: '管理员',
          value: 5
        }
      ]
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'total_space',
    label: '总空间',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 18
    }
  },
  {
    field: 'txt_data_service_list',
    label: '授权秘文端',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Switch',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeText: '启用',
      activeValue: 1301,
      inactiveText: "",
      inactiveValue: 1302
    },
  },
]);
const handleReset = () => {
  const edit = unref(editRef)
  edit?.elFormRef?.resetFields()
}
const controlFormSchema = reactive<FormSchema[]>([
  {
    field: 'flow_read',
    label: '流量读限制',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    }, colProps: {
      span: 20
    }
  },
  {
    field: 'flow_write',
    label: '流量写限制',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    }, colProps: {
      span: 20
    }
  },
  {
    field: 'flow_cycle',
    label: '流量统计类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '小时',
          value: 0
        },
        {
          label: '天',
          value: 1
        },
        {
          label: '周',
          value: 2
        },
        {
          label: '月',
          value: 3
        }
      ]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'max_files',
    label: '最大数量上线',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    }, colProps: {
      span: 20
    }
  },
  {
    field: 'max_files_bytes',
    label: '文件占用空间上线',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    }, colProps: {
      span: 20
    }
  },
]);
const controlDialogVisible = ref(false);
const loadingControl = ref(false);
const controlCurrentObj = ref<WorkControlData>();
const editControlRef = ref<ComponentRef<typeof EditControl>>()
const handleControlReset = () => {
  const control = unref(editControlRef)
  control?.elFormRef?.resetFields()
}
const saveControl = async () => {
  const control = unref(editControlRef)
  await control?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loadingControl.value = true
      const data = (await control?.getFormData()) as WorkControlData
      const res = await saveWorkControlApi(data)
        .catch(() => {
        })
        .finally(() => {
          loadingControl.value = false
        })
      if (res) {
        controlDialogVisible.value = false
        ElMessage.success(res.msg);
      }
    }
  })
}

const handleControlButton = async (row: WorkData) => {
  getWorkControlApi(row.user_id, row.company_id).catch(() => { })
    .then(res => {
      controlCurrentObj.value = res?.data;
      controlDialogVisible.value = true
    }).catch(()=>{
      ElMessage.error("加载数据失败，请联系管理员");
    })
}

const handleDownload = (type) => {
  const url = {
    cj: "work.xlsx",
    kz: "control.xlsx"
  };
  const fileName = url[type];
  downloadStatic(`/static/excel/${fileName}`,fileName);
}

const companyList = ref([] as OrgData[]);

getSelectOrgListApi().then(res => {
  companyList.value = res.data
})
</script>

<template>
  <ContentWrapNoHeaderLine title="沙箱管理">
    <div class="flex justify-between">
      <el-form :inline="true" ref="queryFormRef" :model="queryModel">
        <el-form-item>
          <el-space direction="horizontal" :size="0">
            <el-select v-model="queryModel.company_id" placeholder="组织机构">
              <el-option v-for="item in companyList" :label="`${item.name}`" :key="item.companyId"
                :value="`${item.companyId}`" />
            </el-select>
            <el-input v-model="queryModel.alias" placeholder="别名">
              <template #append>
                <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
              </template>
            </el-input>
          </el-space>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDownload('cj')">创建模板下载</el-button>
          <el-button @click="handleDownload('kz')">控制模板下载</el-button>
        </el-form-item>
      </el-form>
      <el-button :icon="icons.plusIcon" type="primary" @click="handleAdd">新增沙箱</el-button>
    </div>
    <div class="rounded bg-gray-100 w-full flex justify-between px-1.5 py-2 mb-3.5">
      <el-space :size="10" :spacer="spacer">
        <div>已批量选择<span class="mx-1 text-[var(--el-color-primary)]">{{ selectedCount }}</span>条事项</div>
        <div class="flex upload-toolbar">
          <el-button :icon="icons.deleteIcon" link @click="handleDeleteButton(null, true)">批量删除</el-button>
          <ElDivider direction="vertical" style="margin-top: auto;"/>
          <el-upload :action="`${PATH_URL}/work/imp`" :limit="1">
            <el-button :icon="icons.plusIcon" link>批量创建</el-button>
          </el-upload>
          <ElDivider direction="vertical" style="margin-top: auto;"/>
          <el-upload :action="`${PATH_URL}/user/control/imp`" :limit="1">
            <el-button :icon="icons.controlIcon" link>批量控制</el-button>
          </el-upload>
        </div>
      </el-space>
      <el-space :size="10">
        <el-dropdown trigger="click" :hide-on-click="false">
          <span class="el-dropdown-link">
            <Icon icon="icon-park-outline:config" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <div class="flex flex-col p-2">
              <template v-for="column in columns">
                <el-checkbox
v-if="column.field !== 'action'" v-model="column.visible" :label="column.label"
                  :key="column.field" size="small" @change="handleVisibleChange(column)" />
              </template>
            </div>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <Icon icon="bi:download" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出到Csv</el-dropdown-item>
              <el-dropdown-item>导出到Excle</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <Icon icon="bi:printer" class="cursor-pointer " />
      </el-space>
    </div>
    <div class="">
      <Table
border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
        :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
        @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
        <template #state="{ row }">
          <template v-for="so in stateOptions">
            <template v-if="so.value === row.state">
              {{ so.label }}
            </template>
          </template>
        </template>
        <template #used_space="{ row }">
          {{ row.used_space }}/{{ row.total_space }}
        </template>
        <template #action="{ row }">
          <el-space :size="6" :spacer="spacer">
            <ElButton type="primary" link @click="handleControlButton(row)">
              控制
            </ElButton>
            <ElButton type="primary" link @click="handleEditButton(row)">
              编辑
            </ElButton>
            <ElButton type="primary" link @click="handleDeleteButton(row, false)">
              删除
            </ElButton>
          </el-space>
        </template>
      </Table>
    </div>
  </ContentWrapNoHeaderLine>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="470" :max-height="550">
    <Edit ref="editRef" :form-schema="formSchema" :current-row="tableObject.currentRow" />

    <template #footer>
      <ElButton @click="handleReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="save">
        提交
      </ElButton>
    </template>
  </Dialog>

  <Dialog v-if="controlDialogVisible" v-model="controlDialogVisible" title="控制" :width="470" :max-height="300">
    <EditControl ref="editRef" :form-schema="controlFormSchema" :current-row="controlCurrentObj" />

    <template #footer>
      <ElButton @click="handleControlReset">重置</ElButton>
      <ElButton type="primary" :loading="loadingControl" @click="saveControl">
        提交
      </ElButton>
    </template>
  </Dialog>
</template>

<style scoped>
.upload-toolbar>div {
  display: flex;
}
</style>